package com.y.mytest.utils.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtil {

    static final String GET = "GET";
    static final String POST = "POST";
    static final String HEAD = "HEAD";
    static final String OPTIONS = "OPTIONS";
    static final String PUT = "PUT";
    static final String DELETE = "DELETE";
    static final String TRACE = "TRACE";

    public static void sendPostRequest(String url, Map<Object, Object> allData) {
        HttpUtil.sendHttpRequest(url, POST, allData);
    }

    public static void sendHttpRequest(String url, String type, Map<Object, Object> allData) {
        final String AUTH_KEY_FCM = "AAAAHKyyHXs:xxx";
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod(type);
            conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
            conn.setRequestProperty("Content-Type", "application/json; UTF-8");//不设置默认发送文本格式。设置就是json
            conn.setConnectTimeout(3 * 60000);//超时时间
            conn.setReadTimeout(3 * 60000);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(JSON.toJSONString(allData, SerializerFeature.WriteMapNullValue));//转json字符串&保留map空值
            wr.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            wr.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
